//------------------------------------------------------------------------------
// <copyright file="Rpc.WindowsSample.cpp" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

#include "stdafx.h"
#include <Windows.h>
#include "RpcServer.h"
#include "RpcHooks.h"
#include <RpcArchive.h>
#include <RpcErrorCodes.h>
#include <roapi.h>
#include <string>
#include <iostream>


using namespace Microsoft::Internal::GamesTest::Rpc::Server;
using std::cout;
using std::cin;

HANDLE hEndReqeustProcessingEvent;

DWORD WINAPI RequestProcessingThread(void* notUsed)
{
	while(WaitForSingleObject(hEndReqeustProcessingEvent, 0) == WAIT_TIMEOUT)
	{
		Microsoft::Internal::GamesTest::Rpc::Server::TestHooks::ProcessPendingRequests();

		Sleep(100);
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	RoInitialize(RO_INIT_MULTITHREADED);

	int port = 0;

	if (argc > 0)
	{
		port = _wtoi(argv[argc - 1]);
	}

	Microsoft::Internal::GamesTest::Rpc::Server::TestHooks::Initialize(port);
	
	hEndReqeustProcessingEvent = CreateEvent(NULL, false, false, NULL);

	HANDLE hRequestProcessingThread = CreateThread(NULL, 0, RequestProcessingThread, NULL, 0, NULL);
	
	int input = '\0';
	while(input != 'q')
	{
		printf("(E): Raise an event\n");
		printf("(Q): Quit the application\n");
		input = getchar();
		input = tolower(input);

		switch (input)
		{
		case 'e':
			{
				RpcArchive eventName;
				eventName.SetNamedStringValue(L"eventName", L"SampleTestEvent");
				RpcArchive notUsed;
				Microsoft::Internal::GamesTest::Rpc::Server::TestHooks::TriggerEvent(eventName, notUsed);
				break;
			}
		default:
			break;
		}
	}
	
	SetEvent(hEndReqeustProcessingEvent);

	CloseHandle(hRequestProcessingThread);

	return 0;
}

